package com.travelplanning.admin.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.travelplanning.admin.common.biz.user.UserContext;
import com.travelplanning.admin.common.biz.user.UserInfoDTO;
import com.travelplanning.admin.util.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * JWT验证拦截器
 */
@Slf4j
@Component

public class JWTInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public JWTInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();
        //令牌建议是放在请求头中，获取请求头中令牌
        String token = request.getHeader("token");
        log.info("这是获取到的登录令牌"+token);
        if (token==null){
            map.put("code","1");
            map.put("msg","用户未登录");
            map.put("state",false);
            String json = new ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(json);
            return false;
        }
        try{
            JWTUtils.verify(token);//验证令牌
            DecodedJWT decodedJWT = JWTUtils.getToken(token);
            String username = decodedJWT.getClaim("username").asString();
            Object userInfoJsonStr = stringRedisTemplate.opsForHash().get("login_" + username, token);
            UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserInfoDTO.class);
            UserContext.setUser(userInfoDTO);
            stringRedisTemplate.expire("login_"+username,30L, TimeUnit.DAYS);
            return true;//放行请求
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("code","1");
            map.put("msg","无效签名");

        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("code","1");
            map.put("msg","token过期");

        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("code","1");
            map.put("msg","token算法不一致");

        } catch (Exception e) {
            e.printStackTrace();
            map.put("code","1");
            map.put("msg","token失效");

        }
        map.put("state",false);//设置状态
        //将map转化成json，response使用的是Jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }
}

